package cn.mlong.demo.git

import com.intellij.openapi.options.Configurable
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JTextField
import javax.swing.JLabel
import javax.swing.JButton
import javax.swing.JFileChooser
import java.awt.BorderLayout
import java.awt.FlowLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener

class GitBashConfigurable : Configurable {
    private lateinit var panel: JPanel
    private lateinit var pathField: JTextField
    private val settings = GitBashSettings.instance

    override fun createComponent(): JComponent {
        panel = JPanel(BorderLayout())

        val contentPanel = JPanel(FlowLayout(FlowLayout.LEFT))
        contentPanel.add(JLabel("Git Bash 路径:"))

        pathField = JTextField(settings.gitBashPath, 30)
        contentPanel.add(pathField)

        val browseButton = JButton("浏览...")
        browseButton.addActionListener(BrowseButtonListener())
        contentPanel.add(browseButton)

        panel.add(contentPanel, BorderLayout.NORTH)
        return panel
    }

    override fun isModified(): Boolean {
        return pathField.text != settings.gitBashPath
    }

    override fun apply() {
        settings.gitBashPath = pathField.text
    }

    override fun reset() {
        pathField.text = settings.gitBashPath
    }

    override fun getDisplayName(): String {
        return "Git Bash"
    }

    private inner class BrowseButtonListener : ActionListener {
        override fun actionPerformed(e: ActionEvent) {
            val fileChooser = JFileChooser()
            fileChooser.fileSelectionMode = JFileChooser.FILES_ONLY
            fileChooser.dialogTitle = "选择 Git Bash 可执行文件"

            if (fileChooser.showOpenDialog(panel) == JFileChooser.APPROVE_OPTION) {
                pathField.text = fileChooser.selectedFile.absolutePath
            }
        }
    }
}